var common = require('../../utils/common.js');
const app = getApp()
Page({
  data: {
    solitaire: [],
    solitaireId: '',
    item:[],
    logined: false,
    hasShop: false,
    fromapp: false,
    linkAppid: 'wx13e41a437b8a1d2e',
    path:'',
    url:'',
    options:'',
    showShareTip: false,
    isloaded: false,
    fromUserId: '',
    imgbgsrc: '',
    loading: false,
    shareimg1: '',
    fromShopkeeper: false,
    statusBarHeight: app.globalData.statusBarHeight,
    processing: true
  },
  onLoad: function (option) {
    console.log(option)
    console.log(app.globalData.path)
    console.log(this.data.url, this.data.options)
    if (option){
      this.setData({
        solitaireId: option.solitaireId,
        fromUserId: option.userId
      })
    }
    if (wx.getStorageSync('sessionId')) {
      this.setData({
        logined: true,
        sessionId: wx.getStorageSync('sessionId')
      })
      this.getSolitaireData()
      this.getShopData()
    }else{
      // this.loginTip()
      this.setData({
        logined: true,
      })
      this.getSolitaireData()
    }
  },
  onShow(res){
    wx.hideHomeButton()
    console.log(res)
    // this.getpic()
  },
  onShareAppMessage: function () {
    let imageUrl = this.data.imgSrcSmall,
        path = '/pages/shareSolitaireD/shareSolitaireD?solitaireId=' + this.data.solitaireId + '&userId=' + app.globalData.userInfo.userId,
        title = this.data.solitaire.organizer.nickName + '邀请你参加接龙'
    console.log(path)
    return {
      title: title,
      imageUrl: imageUrl,
      path: path
      
    }
  },
  getSolitaireData() {
    wx.showLoading({
      title: '加载中',
    })
    const that = this
    common.post({
      url: '/app/v2/skusolitaire/info', data: { solitaireId: this.data.solitaireId, sessionId: this.data.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          if (res.data.data.sku.images){
            var imgstr = JSON.parse(res.data.data.sku.images)
            console.log(imgstr)
          }
          that.setData({
            solitaire: res.data.data,
            item: res.data.data.sku,
            isloaded: true,
            itemPic: imgstr,
            actEndTime: res.data.data.endTime
          })
          that.countDown()
          setTimeout(function () {
            that.setData({
              loaded: true
            })
            wx.hideLoading()
          }, 2000)
          wx.setNavigationBarTitle({
            title: that.data.solitaire.title
          })
          console.log(that.data.item)
          that.getitemlink()
          console.log(that.data.solitaire)
          that.getpic()
        } else if (res.data.code == -9998) {
          wx.hideLoading()
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  loginTip() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '你需要登录，才能享受优惠',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.runLogin()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  runLogin() {
    const that = this
    let res = app.login(app.globalData.thisshareTicket)
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (that.data.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          console.log('登录')
          that.getSolitaireData()
          that.getShopData()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });
  },
  getitemlink() {
    const that = this
    if (this.data.sessionId) {
      that.linkData(1)
    } else {
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.linkData(2)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  async linkData(e) {
    if (e == 2) {
      console.log(2)
      await app.login(app.globalData.thisshareTicket)
      // await this.link()
    } else {
      console.log(1)
      this.link()
    }

  },
  async link() {
    const that = this
    var couponId
    if (this.data.item.coupons) {
      couponId = this.data.item.coupons[0].couponId
    } else {
      couponId = ''
    }
    var fromUserId =''
    if(this.data.fromUserId !== undefined){
      fromUserId = this.data.fromUserId
    }else{
      fromUserId = ''
    }
    common.post({
      url: '/app/goods/getLink', 
      data: {
        skuId: that.data.item.skuId,
        couponId: couponId,
        sessionId: this.data.sessionId,
        pUserId: fromUserId
      }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          that.setData({
            link: res.data.link,
            logined: true
          });
          var link = encodeURIComponent(that.data.link)
          console.log(that.data.item.sku)
          var path = '/pages/product/product?wareId=' + that.data.item.sku + '&spreadUrl=' + link + '&customerinfo=' + that.data.customerinfo
          console.log(path)
          that.setData({
            item: app.globalData.item,
            path: path
          });
        } else {
          app.login()
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getShopData(){
    const that = this
    common.post({
      url: '/app/v2/shop/shopInfo', data: { sessionId: this.data.sessionId, userId: this.data.fromUserId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          console.log(res.data.data.status)
          if (res.data.data.status == 2){
            that.setData({
              hasShop: true
            })
            
          }
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  buybtnlink: function () {
    const that = this
    console.log(this.data.sessionId)
    if (this.data.sessionId) {
      wx.navigateToMiniProgram({
        appId: this.data.linkAppid,
        path: this.data.path,
        extraData: {
          foo: 'bar'
        },
        success(res) {
          console.log(res)
          // 打开成功
          that.shareSolitaireTip()
          that.joinSolitaire()
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            app.login(app.globalData.thisshareTicket)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }

  },
  toIndex() {
    wx.switchTab({
      url: '/pages/itemlist/itemlist',
      success: function (res) {
        console.log('toItemlist')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toUsercenter() {
    wx.switchTab({
      url: '/pages/usercenter/usercenter',
      success: function (res) {
        app.globalData.fromShopkeeper = true
        console.log('toUsercenter')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toIndex(){
    wx.switchTab({
      url: '/pages/itemlist/itemlist',
      success: function (res) {
        app.globalData.fromShopkeeper = true
        console.log('toItemlist')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toStore(){
    console.log(this.data.userId)
    wx.navigateTo({
      url: '/pages/shareShop/shareShop?userId=' + this.data.fromUserId,
      success: function (res) {
        console.log('toShareShop')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  shareSolitaireTip(){
    this.setData({
      showShareTip: true
    })
  },
  clickShareBtn(){
    this.setData({
      showShareTip: false
    })
    console.log(app.globalData.path)
  },
  joinSolitaire(){
    const that = this
    common.post({
      url: '/app/v2/skusolitaire/join', data: { sessionId: this.data.sessionId, solitaireId: this.data.solitaireId }
    })
      .then((res) => {
        console.log(res.data)
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  getpic() {
    wx.showLoading({
      title: '接龙生成中...',
    })
    const that = this
    var imgbgsrc = this.data.solitaire.sku.image
    wx.getImageInfo({
      src: imgbgsrc,
      success: function (res) {
        that.setData({
          imgbgsrc: res.path
        })
        console.log(that.data.imgbgsrc)
      }
    })
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (that.data.imgbgsrc !== '') {
          clearInterval(timer);
          resolve(that.data);
          that.getSharePic()
        } else {

        }
      }, 250);
    });
  },
  getSharePic() {
    const that = this
    var str1 = this.data.solitaire.title
    var str2 = '我要接龙'
    const sharepic = wx.createCanvasContext('myCanvas')
    console.log(that.data.imgbgsrc)
    sharepic.drawImage(that.data.imgbgsrc, 0, -40, 500, 500)
    sharepic.setFillStyle('#fff')
    sharepic.fillRect(0, 0, 500, 40)
    sharepic.setFillStyle('#fff')
    sharepic.fillRect(0, 320, 500, 80)
    sharepic.setTextAlign('left')
    sharepic.setFontSize(20)
    sharepic.setFillStyle('#333')
    sharepic.fillText(str1, 20, 25)
    sharepic.arc(50, 360, 30, 0, Math.PI * 2, false);
    sharepic.setFillStyle('#f95050')
    sharepic.fill()
    sharepic.arc(450, 360, 30, 0, Math.PI * 2, false);
    sharepic.setFillStyle('#f95050')
    sharepic.fill()
    sharepic.setFillStyle('#f95050')
    sharepic.fillRect(50, 330, 400, 60)
    sharepic.setFontSize(26)
    sharepic.setTextAlign('center')
    sharepic.setFillStyle('#fff')
    sharepic.fillText(str2, 250, 370)
    sharepic.draw(false, function (e) {
      console.log(e)
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 500,
        height: 400,
        destWidth: 500,
        destHeight: 400,
        canvasId: 'myCanvas',
        success: function (res) {
          console.log(res.tempFilePath)
          that.setData({
            shareimg1: res.tempFilePath,
            imgShow: true,
            loading: true,
          });
          wx.hideLoading()
        },
        fail(res) {
          console.log(res)
        }
      })
    })
  },
  countDown() {//倒计时函数
    const that = this
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = new Date(this.data.actEndTime).getTime();
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    // let endTime = new Date(endTimeList).getTime();
    let endTime = endTimeList;
    // console.log(endTime, newTime)
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      // let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 48) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        // day: this.timeFormat(day),
        hou: this.timeFormat(hou),
        min: this.timeFormat(min),
        sec: this.timeFormat(sec)
      }
      setTimeout(this.countDown, 1000);
    } else {//活动已结束，全部设置为'00'
      obj = {
        // day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
      that.setData({
        processing: false
      })
    }
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ 
      countDownList: obj
    })
    // console.log(this.data.countDownList)
  },
  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  toShopBtn(){
    wx.navigateTo({
      url: '/pages/shareShop/shareShop?userId=' + this.data.fromUserId,
      success: function (res) {
        console.log('toInitiateJl')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  shareJl(){
    if(this.data.processing){
      this.canvas()
    }
    
  },
  // 选择画布
  canvas(){
    wx.showLoading({
      title: '分享图生成中',
      mask: true
    })
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render(canvas, ctx);
    }).exec()
  },
  canvas1(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render2(canvas, ctx);
    }).exec()
  },
 
  // 生成分享图

  render(canvas, ctx) {
    const that = this
    this.drawIteminfo(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemPic(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawItemTag(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawAvatar(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawDcode(ctx,canvas).then(function(){
              console.log('第五步完成')
              that.drawjlinfo(ctx,canvas).then(function(){
                console.log('第六步完成')
                that.drawCanvas(canvas)
                that.canvas1()
              })
            })
          })
        })
      })
    })
  },
  render2(canvas, ctx){
    const that = this
    that.drawSmallpic(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawSmalltag(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawCanvas2(canvas)
      })
    })
  },
  // 绘制分享小图
  drawSmallpic(ctx,canvas){
    const that = this
    let item = this.data.solitaire.sku,
        txt1 = '这个超值商品好多人都在抢购呢！',
        txt2 = '已经' + this.data.solitaire.partnerCount + '人参与了接龙>'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 500);
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,320,500,80)
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 16, 351);
        ctx.fillStyle = "#FFF617";
        ctx.fillText(txt2, 16, 385);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 绘制商品标签
  drawSmalltag(ctx,canvas){
    const that = this
    let item = this.data.solitaire.sku
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 12, 12, 200, 36);
        ctx.font = "20px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 146, 38);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 46, 38);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制内容
  drawIteminfo(ctx,canvas){
    console.log('开始绘图')
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 18) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 19) {
          finalStr += name[i];
        }
        if (length > 35) {
          break;
        }
      }
      return finalStr + '...';
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    let item = this.data.solitaire.sku,
        solitaire = this.data.solitaire,
        itemName = item.title,
        str1 = row1size(itemName),
        str2 = row2size(itemName),
        priceNew = '',
        priceOld = format(item.price),
        priceNewTxt = '抢券价',
        priceOldTxt = '京东价'
        // txt1 = solitaire.partnerCount + '人参与了群接龙567'
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        ctx.font = "30px PingFangSC-Medium";
        ctx.fillStyle = "#363636";
        ctx.textAlign = 'center';
        ctx.fillText(str1, 414, 904);
        ctx.fillText(str2, 414, 946);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.fillText(priceNewTxt, 303, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceNew, 303, 1058);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#505050";
        ctx.fillText(priceOldTxt, 530, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceOld, 530, 1058);
        let lineWidth = ctx.measureText(priceOld).width
        console.log('线长度',lineWidth)
        ctx.beginPath()
        ctx.strokeStyle = '#D6D6D6'
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1008)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1044)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.strokeStyle = '#505050'
        ctx.lineWidth = 2;
        let lineX1 = 530 - lineWidth/2,
            lineX2 = 530 + lineWidth/2
        ctx.moveTo(lineX1, 1040)
        ctx.lineTo(lineX2, 1040)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/zc_share@3x.jpg'
    })
  },
  drawjlinfo(ctx,canvas){
    let txt = this.data.solitaire.partnerCount + '人参与了群接龙'
    let x = 120,y = 1120, r = 36, w = 600, h = 72
    const that = this;
    return new Promise(function (resolve, reject) {
      ctx.save()
      ctx.beginPath()
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      // 这里是使用 fill 还是 stroke都可以，二选一即可
      ctx.setFillStyle = 'transparent'
      // ctx.setStrokeStyle('transparent')
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      // 右上角
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
      // 左下角
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.strokeStyle = '#FF5555'
      ctx.lineWidth = '2'
      ctx.stroke()
      ctx.closePath()
      // 剪切
      ctx.clip()
      ctx.restore();
      ctx.textAlign = 'center';
      ctx.fillStyle = "#FF5555";
      ctx.font = "32px PingFangSC-Medium";
      ctx.fillText(txt, 414, 1165);
      resolve()
    })
  },
  // 绘制商品图
  drawItemPic(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        var x = 134,y = 264, r = 8, w = 560, h = 560
        ctx.save()
        ctx.beginPath()
        // ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, 134, 264, 560, 560);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.solitaire.sku.image
    })
  },
  // 绘制标签
  drawItemTag(ctx,canvas){
    const that = this
    let item = this.data.solitaire.sku
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 292, 798, 244, 52);
        ctx.font = "26px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 454, 834);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 330, 834);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制头像
  drawAvatar(ctx,canvas){
    const that = this
    let txt1 = this.data.solitaire.organizer.nickName + ' 邀请你参与接龙',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.solitaire.organizer.avatar
    })
  },
  // 绘制二维码
  drawDcode(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId + '&solitaireId=' + that.data.solitaire.solitaireId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/shareSolitaireD/shareSolitaireD',
          page: 'pages/itemlist/itemlist',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 生成图片
  drawCanvas(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          wx.hideLoading()
        }
      })
    })
  },
  drawCanvas2(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true
          })
          wx.hideLoading()
        }
      })
    })
  },
  saveSharePic(){
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imgSrc,
      success: function (data) {
          wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
          })
      },
      fail: function (err) {
          console.log(err);
          if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                  success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                  }
              })
          } else {
              wx.showToast({
                  title: '保存失败',
                  icon: 'none'
              });
          }
      },
      complete(res) {
          console.log(res);
      }
    })
  },
  closeSharePic(){
    console.log('关闭')
    this.setData({
      showshareBox: false
    })
  },
})